package cn.kgc.controller;

import cn.kgc.config.WechatConfig;
import cn.kgc.dto.UsersDto;
import cn.kgc.service.UsersService;
import cn.kgc.utils.UrlUtils;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@Controller
public class WechatController {

    private final WechatConfig wechatConfig;
    private final UsersService usersService;

    public WechatController(WechatConfig wechatConfig, UsersService usersService) {
        this.wechatConfig = wechatConfig;
        this.usersService = usersService;
    }

    @GetMapping("/wxlogin")
    public void getCode(String code, HttpServletResponse response) throws IOException {
        log.info("微信传递的code: {}", code);
        String url = "https://api.weixin.qq.com/sns/oauth2/access_token?" +
                "appid=%s&" +
                "secret=%s&" +
                "code=%s" +
                "&grant_type=authorization_code";
        String resultJson = UrlUtils.loadURL(String.format(url, wechatConfig.getAppid(), wechatConfig.getSecret(), code));
        log.info("resultJson: {}", resultJson);
        // 解析json
        HashMap<String, String> map = JSON.parseObject(resultJson, HashMap.class);
        String access_token = map.get("access_token").toString();
        String openid = map.get("openid");
        UsersDto usersDto = usersService.loginByWechat(access_token, openid);
        String token = usersDto.getToken();
        String userName = usersDto.getUserName();
        response.sendRedirect(wechatConfig.getSuccess_url() + "?token=" + token + "&userInfo=" + userName);
    }

    @PostMapping("/info")
    public Map<String,Object> getInfo(String token){

        Map<String, Object> map = usersService.getInfo(token);
        return map;
    }
}
